<template>
  <div class="container">
    <!-- 头部 -->
    <div class="header">
      <h1>新增轮播图</h1>
      <el-button type="primary" plain @click="handleBack">返回</el-button>
    </div>

    <!-- 表单区域 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- 轮播图标题 -->
      <el-form-item label="轮播图标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入..." clearable />
      </el-form-item>

      <!-- 轮播图上传 -->
      <el-form-item label="轮播图" prop="image">
        <div class="image-upload-container">
          <el-upload
            class="image-uploader"
            action="http://localhost:5260/api/Carouselimage/UploadImage"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <div v-if="form.image" class="image-preview">
              <img :src="form.image" class="preview-image" />
              <div class="image-actions">
                <el-button
                  type="danger"
                  circle
                  size="small"
                  @click.stop="handleRemoveImage"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸375 * 211，不要超过1M</div>
        </div>
      </el-form-item>

      <!-- 轮播图状态 -->
      <el-form-item label="轮播图状态">
        <el-switch
          v-model="form.status"
          inline-prompt
          active-text="开"
          inactive-text="关"
        />
      </el-form-item>

      <!-- 链接地址 -->
      <el-form-item label="轮播图链接地址" prop="link">
        <el-input v-model="form.link" placeholder="请输入..." clearable />
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="1"
          placeholder="请输入..."
          controls-position="right"
        />
        <span class="sort-tip">填写数字，数字越大越靠前</span>
      </el-form-item>

      <!-- 操作按钮 -->
      <div class="form-footer">
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
const router = useRouter();

const formRef = ref();
const form = reactive({
  title: '',
  image: null,
  status: true,
  link: '',
  sort: null
});

// 验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  image: [{ required: true, message: '请上传轮播图', trigger: 'change' }],
  link: [{ required: true, message: '请输入链接地址', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
};

// 文件上传处理
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 1;

  if (!isJPG) {
    ElMessage.error('只能上传JPG格式图片!');
    return false;
  }
  if (!isLt1M) {
    ElMessage.error('图片大小不能超过1MB!');
    return false;
  }
  return true;
};

const handleUploadSuccess = (response) => {
  if (response && response.url) {
    // 确保URL是完整的
    const imageUrl = response.url.startsWith('http')
      ? response.url
      : `http://localhost:5260${response.url}`;
    form.image = imageUrl;
    ElMessage.success('图片上传成功!');
  } else {
    ElMessage.error('图片上传失败!');
  }
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试');
};

const handleRemoveImage = (event) => {
  event.stopPropagation(); // 阻止事件冒泡
  form.image = null;
  ElMessage.success('图片已删除');
};

import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    // 组装接口数据
    const payload = {
      carouselTitle: form.title,
      thumbnail: form.image, // 现在是url
      status: form.status ? 1 : 0,
      carouselLinkAddress: form.link,
      sorting: form.sort,
      createName: store.ccstore.nickName, // 可替换为实际用户名
      createTime: new Date().toISOString()
    };
    // 发送POST请求
    const res = await axios.post(
      'http://localhost:5260/api/Carouselimage/Carouselimage',
      payload
    );
    if (res.data && res.data.code === 212) {
      ElMessage.success('提交成功!');
      handleCancel();
    } else {
      ElMessage.error(res.data.msg || '提交失败!');
    }
  } catch (error) {
    console.error('验证失败:', error);
    ElMessage.error('请检查表单内容');
  }
};

// 取消操作
const handleCancel = () => {
  formRef.value.resetFields();
};

// 返回操作
const handleBack = () => {
  router.push('/CarouselimageQuery');
};
</script>

<style scoped>
.container {
  padding: 20px;
  background: white;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-uploader {
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 375px;
  height: 211px;
}

.image-uploader:hover {
  border-color: var(--el-color-primary);
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 375px;
  height: 211px;
  text-align: center;
  line-height: 211px;
}

.image-preview {
  position: relative;
  width: 375px;
  height: 211px;
}

.preview-image {
  width: 375px;
  height: 211px;
  display: block;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.sort-tip {
  color: #999;
  margin-left: 10px;
  font-size: 12px;
}

.form-footer {
  margin-top: 30px;
  text-align: right;
}
</style>
